package com.shamrock.oauth.api.service;
import com.shamrock.oauth.api.entity.User;
import com.shamrock.oauth.api.httpclient.AccessToken;
import com.shamrock.oauth.api.httpclient.HttpClients;
import com.shamrock.oauth.api.httpclient.PostParameter;
import com.shamrock.oauth.util.Config;
import com.shamrock.oauth.util.JSONObject;
/**
 * 新浪微博登录Api
 * 第一步：授权，获取code
 * 第二步：通过code,获取accessToken及uid
 * 第三步:通过accessToken、openid获取用户信息
 * @author GunnyZeng
 *
 */
public class SinaWeiboOAuthApi implements OAuthApiService{
	

	
	private String client_ID = Config.getValue("sinaweibo_client_ID").trim();
	private String client_SERCRET = Config.getValue("sinaweibo_client_SERCRET").trim();
	private String redirect_URI = Config.getValue("sinaweibo_redirect_URI").trim();
	private String baseURL = Config.getValue("sinaweibo_baseURL").trim();
	private String accessTokenURL = Config.getValue("sinaweibo_accessTokenURL").trim();
	private String authorizeURL = Config.getValue("sinaweibo_authorizeURL").trim();
	private String typeid = Config.getValue("sinaweibo_typeid").trim();
	HttpClients client  = new HttpClients();

	/**
	 * 跳转授权操作
	 */
	@Override
	public String authorize() {
		return authorizeURL+ "?client_id="+ client_ID+ "&redirect_uri="+ redirect_URI+ "&response_type=code&state=";
	}
	/**
	 * 授权后获取用户
	 * @throws Exception 
	 */
	@Override
	public User getUser(Object parame) throws Exception {
	
		String code = (String) parame;
		AccessToken accessToken = getAccessToken(code);
		JSONObject json = showUser(accessToken);
        User user = new User();
        user.setId(json.getString("id"));
        user.setProvince(json.getString("province"));
        user.setCity(json.getString("city"));
        user.setLocation(json.getString("location"));
        user.setAvatarLarge(json.getString("avatar_large"));
        user.setGender(json.getString("gender"));
        user.setNickName(json.getString("screen_name"));
        user.setSource("新浪微博");
        return user;
	}
	/**
	 * 获取AccessToken
	 * @param code
	 * @return
	 * @throws Exception 
	 */
	private AccessToken getAccessToken(String code) throws Exception{
		return new AccessToken(client.post(
				accessTokenURL,
				new PostParameter[] {
						new PostParameter("client_id", client_ID),
						new PostParameter("client_secret",client_SERCRET),
						new PostParameter("grant_type", "authorization_code"),
						new PostParameter("code", code),
						new PostParameter("redirect_uri", redirect_URI) }, 
				false, 
				null),typeid);
        
	}
	/**
	 * 授权后获取用户json数据
	 * @param accessToken
	 * @return
	 * @throws Exception 
	 */
	private JSONObject showUser(AccessToken accessToken) throws Exception{
		return client.get(baseURL+ "users/show.json",
				new PostParameter[] { 
						new PostParameter("uid", accessToken.getUserUid()) },
				accessToken.getAccessToken()
				).asJSONObject();
        
	}
	
}
